package org.viva.core.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class IMG {
	public static final String	TYPE_JPG	= "jpg";
	public static final String	TYPE_PNG	= "png";

	/**
	 * 图像压缩
	 * 
	 * @param is
	 *            图像输入流
	 * @param fileType
	 *            图像类型
	 * @param maxWidth
	 *            最大宽度
	 * @param maxHeight
	 *            最大高度
	 * @return
	 * @throws IOException
	 */
	public byte[] shrink(InputStream is, String fileType, int maxWidth, int maxHeight) throws IOException {
		BufferedImage src = ImageIO.read(is); // 读入文件
		int width = src.getWidth();
		int height = src.getHeight();
		if (width > maxWidth) {
			width = maxWidth;
			height = src.getHeight() * maxWidth / src.getWidth();
		}
		if (height > maxHeight) {
			width = maxHeight * src.getWidth() / src.getHeight();
			height = maxHeight;
		}
		Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);// SCALE_DEFAULT
		BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = tag.getGraphics();
		g.drawImage(image, 0, 0, null);
		g.dispose();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(tag, fileType, bos);
		return bos.toByteArray();
	}

	/**
	 * 图像压缩
	 * 
	 * @param is
	 *            图像输入流
	 * @param fileType
	 *            图像类型
	 * @param maxWidth
	 *            最大宽度
	 * @param maxHeight
	 *            最大高度
	 * @return
	 * @throws Exception
	 */
	public static InputStream shrink2is(InputStream is, String fileType, int maxWidth, int maxHeight) throws Exception {
		BufferedImage src = ImageIO.read(is); // 读入文件
		int width = src.getWidth();
		int height = src.getHeight();
		if (width > maxWidth) {
			width = maxWidth;
			height = src.getHeight() * maxWidth / src.getWidth();
		}
		if (height > maxHeight) {
			width = maxHeight * src.getWidth() / src.getHeight();
			height = maxHeight;
		}
		Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);// SCALE_DEFAULT
		BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = tag.getGraphics();
		g.drawImage(image, 0, 0, null);
		g.dispose();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(tag, fileType, bos);
		return new ByteArrayInputStream(bos.toByteArray());
	}

}
